<template>
  <div class="page gray-page leadership">
    <nav-bar title="领导指挥督办" theme="white">
      <template #custom>
        <img src="@/assets/images/cockpit/home/status-bar-search.png" class="iconimg" alt="" @click="filterClick" />
      </template>
    </nav-bar>
    <div class="list-main page-main" style="margin-top: 44px">
      <div class="command-mapmain" id="container"></div>
      <div class="command-navigation">
        <button @click="navigation">导航</button>
      </div>
      <div class="linkage-command" @click="$router.go(-1)">事件督办</div>
      <van-popup v-model="eventPopupShow" round position="bottom">
        <div class="command-popup-main">
          <van-row class="command-popup-main-content">
            <van-col :span="24">
              <p class="gb-card-info">
                <span class="gb-card-info__label">事件名称</span>
                <span class="gb-card-info__value">{{ eventDetail.eventName }}</span>
              </p>
            </van-col>
            <van-col :span="24">
              <p class="gb-card-info">
                <span class="gb-card-info__label">事件描述</span>
                <span class="gb-card-info__value">{{ eventDetail.eventDescription }}</span>
              </p>
            </van-col>
            <van-col :span="12">
              <p class="gb-card-info">
                <span class="gb-card-info__label">事件来源</span>
                <span class="gb-card-info__value">{{ eventDetail.eventOriginName }}</span>
              </p>
            </van-col>
            <van-col :span="12">
              <p class="gb-card-info">
                <span class="gb-card-info__label">事件规模</span>
                <span class="gb-card-info__value">{{ eventDetail.eventScaleName }}</span>
              </p>
            </van-col>
            <van-col :span="12">
              <p class="gb-card-info">
                <span class="gb-card-info__label">上报人</span>
                <span class="gb-card-info__value">{{ eventDetail.reportPerson }}</span>
              </p>
            </van-col>
            <van-col :span="12">
              <p class="gb-card-info">
                <span class="gb-card-info__label">手机号</span>
                <span class="gb-card-info__value">{{ eventDetail.reportPhone }}</span>
              </p>
            </van-col>
            <van-col :span="24">
              <p class="gb-card-info">
                <span class="gb-card-info__label">事件分类</span>
                <span class="gb-card-info__value">{{ eventDetail.eventTypeName }}</span>
              </p>
            </van-col>
            <van-col :span="24">
              <p class="gb-card-info">
                <span class="gb-card-info__label">上报时间</span>
                <span class="gb-card-info__value">{{ eventDetail.reportTime }}</span>
              </p>
            </van-col>
            <van-col :span="24" v-if="fileList.length">
              <van-cell title="图片/视频" title-class="van-cell__title_gray img-wrap" :border="false" />
              <van-field class="van-field__value--upload">
                <template #input>
                  <van-uploader
                    name="fileList"
                    v-model="fileList"
                    :show-upload="false"
                    :deletable="false"
                    @click-preview="previewClick"
                  >
                    <template #preview-cover="file">
                      <template v-if="format.includes(file.url.split('.')[file.url.split('.').length - 1])">
                        <div class="van-uploader__preview-masker"></div>
                        <video-player
                          class="video-player vjs-custom-skin"
                          :playsinline="true"
                          :options="{
                            aspectRatio: '16:16',
                            preload: 'auto',
                            sources: [
                              {
                                src: file.url
                              }
                            ]
                          }"
                        ></video-player>
                      </template>
                    </template>
                  </van-uploader>
                </template>
              </van-field>
            </van-col>
            <van-col :span="24">
              <p class="gb-card-info">
                <span class="gb-card-info__label">处置状态</span>
                <span class="gb-card-info__value">{{ eventDetail.eventStatusName }}</span>
              </p>
            </van-col>
          </van-row>
        </div>
      </van-popup>
      <van-popup v-model="empPopupShow" round position="bottom">
        <div class="command-popup-main">
          <dl class="gb-card-dl">
            <dt>
              <template v-if="empDetail.personImage">
                <img class="emp-img" :src="$config.ImageURl + empDetail.personImage" alt="" />
              </template>
              <template v-else>
                <img
                  class="emp-img"
                  :src="
                    require(`@/assets/images/inspectVisit/visit/pic_photo_${
                      empDetail.sex === '1' ? 'man' : 'woman'
                    }@2x.png`)
                  "
                  alt=""
                />
              </template>
              <div style="height: 96px"></div>
            </dt>
            <dd class="emp-right">
              <van-row>
                <van-col :span="24">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">所属区域</span>
                    <span class="gb-card-info__value">{{ empDetail.regionName }}</span>
                  </p>
                </van-col>
                <van-col :span="12">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">姓名</span>
                    <span class="gb-card-info__value">{{ empDetail.gridPersonName }}</span>
                  </p>
                </van-col>
                <van-col :span="12">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">类别</span>
                    <span class="gb-card-info__value">{{ empDetail.gridPersonTypeName }}</span>
                  </p>
                </van-col>
                <van-col :span="12">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">性别</span>
                    <span class="gb-card-info__value">{{ empDetail.sexName }}</span>
                  </p>
                </van-col>
                <van-col :span="12">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">民族</span>
                    <span class="gb-card-info__value">{{ empDetail.nationalityName }}</span>
                  </p>
                </van-col>
                <van-col :span="24">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">手机号</span>
                    <span class="gb-card-info__value">{{ empDetail.phone }}</span>
                  </p>
                </van-col>
                <van-col :span="24">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">出生日期</span>
                    <span class="gb-card-info__value">{{ empDetail.birthday }}</span>
                  </p>
                </van-col>
                <van-col :span="24">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">政治面貌</span>
                    <span class="gb-card-info__value">{{ empDetail.politicName }}</span>
                  </p>
                </van-col>
                <van-col :span="24">
                  <p class="gb-card-info">
                    <span class="gb-card-info__label" style="width: auto">学历</span>
                    <span class="gb-card-info__value">{{ empDetail.edulevelName }}</span>
                  </p>
                </van-col>
              </van-row>
            </dd>
          </dl>
        </div>
      </van-popup>
      <model ref="commandModal" @alleventSerch="eventSearch"></model>
      <!-- 视频预览 -->
      <gb-video :url="videoUrl" :show.sync="videoPopupShow"></gb-video>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import mapPlugin from '@/libs/mapPlugin'
import Model from '@/components/Widget/Cockpit/EventOverview/Model/index'
import Cockpit from '@/api/cockpit'
export default {
  components: { Model },
  data() {
    return {
      map: null,
      center: [],
      markers: [],
      overlayGroup: null,
      eventPopupShow: false,
      empPopupShow: false,
      eventDetail: {
        eventName: 'wwww'
      },
      empDetail: {},
      myMarker: [],
      myPos: null,
      northEastPos: [],
      southWest: [],
      timer: null,
      gridEmpsMarkers: [],
      gridEmpsOverlayGroup: null,
      distanceMarker: [],
      eventDatas: [],
      eventMarkers: [],
      eventImgObj: {
        1: 'underdisposal',
        2: 'pending-disposal',
        // 3: 'about-to-timeout',
        4: 'timedout'
      },
      searchData: {},
      locationData: {},
      // 视频后缀
      format: ['mp4', 'avi', 'mov'],
      // 视频弹窗
      videoPopupShow: false,
      videoUrl: '',
      fileList: [],
      // 详情 - 九张图片key
      uploadKeys: [
        'firstImageUrl',
        'secondImageUrl',
        'thirdImageUrl',
        'fourthImageUrl',
        'fifthImageUrl',
        'sixthImageUrl',
        'seventhImageUrl',
        'eighthImageUrl',
        'ninthImageUrl'
      ],
      endPos: []
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    }),
    curPersonImg() {
      return this.user.personImage
        ? this.$config.ImageURl + this.user.personImage
        : 'https://img01.yzcdn.cn/vant/cat.jpeg'
    }
  },
  mounted() {
    this.map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 16
    })
    this.setMyLocation()
    this.map.on('dragend', e => {
      this.mapChange(e)
    })
    this.map.on('zoomend', e => {
      this.mapChange(e)
    })
  },
  methods: {
    mapChange(e) {
      // 地图拖拽/缩放结束重新获取地图显示范围
      console.log(e)
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.getBounds()
      }, 2000)
    },
    eventSearch(searchData) {
      // 事件筛选
      this.searchData = searchData
      this.eventLocation(this.locationData)
    },
    getBounds() {
      // 获取地图显示范围
      const bounds = this.map.getBounds()
      this.northEastPos = [bounds.northEast.lng, bounds.northEast.lat]
      this.southWestPos = [bounds.southWest.lng, bounds.southWest.lat]
      this.locationData = {
        longitude1: this.southWestPos[0],
        longitude2: this.northEastPos[0],
        latitude1: this.southWestPos[1],
        latitude2: this.northEastPos[1]
      }
      this.eventLocation(this.locationData)
    },
    eventLocation(locationData) {
      // 获取事件
      const paramsData = Object.assign(locationData, this.searchData)
      Cockpit.Record.eventLocation(paramsData).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.eventDatas = data
          if (this.eventMarkers.length) {
            this.map.remove(this.eventMarkers)
          }
          // 设置事件标记
          this.eventMarkers = []
          this.eventDatas.forEach(item => {
            if (item.isTimeOut === '1') {
              // 已超时
              item.status = '4'
            }
            if (item.eventStatus === '2' || item.eventStatus === '7') {
              // 待处置
              item.status = '1'
            } else if (item.eventStatus === '3' || item.eventStatus === '8') {
              // 处置中
              item.status = '2'
            }
            const img = require(`@/assets/images/gridMap/event-${this.eventImgObj[item.status * 1]}@2x.png`)
            const content = `
              <div class="amap-marker-event-content">
                  <img src="${img}" class="event-marker" alt="">
                  <div class="marker-info event-name event-name-${item.status}">${item.eventName}</div>
              </div>`
            var marker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              content: content
            })
            this.eventMarkers.push(marker)
            // 点击事件标注，获取步行导航路线
            marker.on('click', e => {
              const distancePos = [(this.myPos[0] + e.lnglat.lng) / 2, (this.myPos[1] + e.lnglat.lat) / 2]
              this.removeDistanceMarker()
              this.walking = mapPlugin.walking(this.map, this.myPos, [e.lnglat.lng, e.lnglat.lat], async res => {
                this.distanceMarker = new AMap.Marker({
                  position: new AMap.LngLat(distancePos[0], distancePos[1]),
                  content: `<div class="marker-info distance-info">距离我${res.routes[0].distance}米</div>`
                })
                this.map.add(this.distanceMarker)
              })
              this.getEventDetail(item.eventCode)
              this.endPos = [e.lnglat.lng, e.lnglat.lat]
            })
          })
          if (this.eventMarkers.length) {
            this.overlayGroup = new AMap.OverlayGroup(this.eventMarkers)
            this.map.add(this.overlayGroup)
            this.map.setFitView(this.eventMarkers)
          }
        }
      })
    },
    surroundingGirdPerson() {
      // 获取周边网格员
      const paramsData = {
        longitude: this.myPos[0],
        latitude: this.myPos[1]
      }
      Cockpit.Record.surroundingGirdPerson(paramsData).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          console.log(data)
          const img = require('@/assets/images/gridMap/gridMap-emp@2x.png')
          const imgActive = require('@/assets/images/gridMap/gridMap-emp-active@2x.png')
          data.forEach(item => {
            item.telephone = item.phone
            const marker = new AMap.Marker({
              position: new AMap.LngLat(item.longitude, item.latitude),
              content: `<img src="${img}" class="emp-marker" alt="">`
            })
            this.gridEmpsMarkers.push(marker)
            marker.on('click', e => {
              e.originEvent.srcElement.outerHTML = `<img src="${imgActive}" class="emp-marker" alt="">`
              const distancePos = [(this.myPos[0] + e.lnglat.lng) / 2, (this.myPos[1] + e.lnglat.lat) / 2]
              this.removeDistanceMarker()
              this.walking = mapPlugin.walking(this.map, this.myPos, [e.lnglat.lng, e.lnglat.lat], async res => {
                this.distanceMarker = new AMap.Marker({
                  position: new AMap.LngLat(distancePos[0], distancePos[1]),
                  content: `<div class="marker-info distance-info">距离我${res.routes[0].distance}米</div><span class="call-btn">视频通话</span>`
                })
                this.map.add(this.distanceMarker)
                this.distanceMarker.on('click', e => {
                  // 视频通话
                  this.$eventBus.$emit('trtcCallingCall', item)
                })
                this.getGirdPersonDetail(item.gridPersonCode)
                this.endPos = [e.lnglat.lng, e.lnglat.lat]
              })
            })
          })
          console.log(this.gridEmpsMarkers)
          if (this.gridEmpsMarkers.length) {
            this.gridEmpsOverlayGroup = new AMap.OverlayGroup(this.gridEmpsMarkers)
            this.map.add(this.gridEmpsOverlayGroup)
            this.map.setFitView(this.gridEmpsMarkers)
          }
        }
      })
    },
    removeDistanceMarker() {
      // 清楚距离我提示文字
      if (this.distanceMarker) {
        this.map.remove(this.distanceMarker)
      }
    },
    getGirdPersonDetail(code) {
      // 获取网格员详情
      Cockpit.Record.girdPersonDetail({
        gridPersonCode: code
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.empDetail = data
          this.empPopupShow = true
        }
      })
    },
    getEventDetail(code) {
      // 获取事件详情
      Cockpit.Record.detail({
        eventCode: code
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          console.log(data)
          this.eventDetail = data
          this.fileList = []
          for (let i = 0; i < this.uploadKeys.length; i++) {
            if (this.eventDetail[this.uploadKeys[i]]) {
              this.fileList.push({
                url: this.$config.ImageURl + this.eventDetail[this.uploadKeys[i]]
              })
            }
          }
          console.log(this.fileList)
          this.eventPopupShow = true
        }
      })
    },
    navigation() {
      // 导航
      if (this.endPos.length > 0) {
        this.$router.push({
          path: '/cockpit/supervise/linkageCommand/NavigationPage',
          query: {
            startLng: this.myPos[0],
            startLat: this.myPos[1],
            endLng: this.endPos[0],
            endLat: this.endPos[1]
          }
        })
      } else {
        this.$toast.fail('请先选择前往的目的地')
      }
    },
    // 视频预览
    previewClick({ file }, detail) {
      const urlArr = this.fileList[detail.index].url.split('.')
      const suffix = urlArr[urlArr.length - 1]
      if (this.format.includes(suffix)) {
        this.videoPopupShow = true
        this.videoUrl = this.fileList[detail.index].url
      }
    },
    filterClick() {
      // 筛选
      this.$refs.commandModal.popUpshow = true
    },
    setMyLocation() {
      // 设置我的位置标记
      mapPlugin.geolocation(res => {
        this.myPos = [res.position.lng, res.position.lat]
        console.log(this.myPos)
        this.myMarker = new AMap.Marker({
          position: new AMap.LngLat(res.position.lng, res.position.lat),
          content: `<img src="${this.curPersonImg}" class="my-location-marker" alt="">`
        })
        this.map.add(this.myMarker)
        this.map.setFitView(this.myMarker)
        this.surroundingGirdPerson()
        this.getBounds()
      })
    }
  }
}
</script>

<style scoped lang="less">
@import '~@/assets/style/cockpit/leadership.less';
@import '~@/assets/style/cockpit/command.less';
</style>
